// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.linqingying.gitcode.util

import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import com.linqingying.gitcode.api.GitCodeServerPath
import com.linqingying.gitcode.authentication.GCAccountsUtil
import com.linqingying.gitcode.authentication.accounts.GCAccountManager
import com.linqingying.gitcode.authentication.accounts.GitCodeAccount

/**
 * Temporary util methods for maintaining compatibility
 */
object GCCompatibilityUtil {
  @JvmStatic
  fun requestNewAccountForServer(serverPath: GitCodeServerPath, project: Project): GitCodeAccount? =
    GCAccountsUtil.requestNewAccount(serverPath, login = null, project = project)?.account

  @RequiresBackgroundThread
  @JvmStatic
  fun getOrRequestToken(account: GitCodeAccount, project: Project): String? {
    val accountManager = service<GCAccountManager>()
    val modality =/* ProgressManager.getInstance().currentProgressModality ?:*/ ModalityState.any()
    return runBlocking {
      accountManager.findCredentials(account)
      ?: withContext(Dispatchers.EDT + modality.asContextElement()) {
        GCAccountsUtil.requestNewToken(account, project)
      }
    }
  }
}
